//
//  Category_Vc_goods.swift
//  Pods
//
//  Created by eme on 2017/6/13.
//
//
import UIKit
import UtilCore
import RickonCore
import AddCarCore
import EmptyDataView
import BrandonCore

class Category_Vc_goods:  Empty_TVc,AddCarProtocol {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var goodsList_TableView: UITableView!        //商品列表
    
    var goodsArr:[CategoryGoodModel]?{                          //商品数据源
        didSet{
            self.goodsList_TableView.reloadData()
        }
    }
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    var CategoryGoodListVm:Category_goodsVm?                    //获取商品列表
    
    let hearder = MJCustomGifHeader()                           //商品顶部刷新
    
    let footer = MJRefreshAutoNormalFooter()                    //商品底部刷新
    
    var pdid:String?                                            //商品ID
    
    var productModel:ProductModel?                              //SKU_Model
    
    var GetSku:GetSkuVm?
    
    var isreloadType = false
    
    var pptid:String?
    
    var pptype:String?
    
    var customtitle:String?
    
    /****************************Storyboard 绑定方法区域****************************/
    func add_JHD(_ sender: UIButton) {
        if let user = AppData.loginedUser{
            if user.glShop.showSpstate == "审核通过"{
                self.GetSku?.getSKU.onNext("\(goodsArr?[sender.tag].pdid ?? "")")
            }else{
                _ = "authvalidation".openURL(["isneedlogin":"1"])
            }
        }else{
            _ = "login".openURL()
        }
    }
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.title = customtitle ?? ""
        //        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.CategoryGoodListVm?.pptid = self.pptid ?? ""
        self.CategoryGoodListVm?.ppturlStatus.value = self.pptid ?? ""
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabBarController?.tabBar.isHidden = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        
        self.goodsList_TableView.dzn_tv_emptyDelegate = self
        self.goodsList_TableView.dzn_tv_emptyDataSource = self
        self.goodsList_TableView.tableFooterView = UIView()
        
        self.goodsList_TableView.showsVerticalScrollIndicator = false
        
        // 上拉刷新
        hearder.setRefreshingTarget(self, refreshingAction: #selector(Category_Vc_goods.headerRefresh))
        self.goodsList_TableView.mj_header = hearder
        
        // 下拉加载更多
        footer.setRefreshingTarget(self, refreshingAction: #selector(Category_Vc_goods.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.goodsList_TableView.mj_footer = footer
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
    }
    //------
    //下拉加载
    func footerRefresh(){
        self.footer.endRefreshing()
    }
    //---
    //上拉刷新
    func headerRefresh(){
        
        self.hearder.endRefreshing()
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //-----------------------------------------------
        //获取分类对应的商品
        self.CategoryGoodListVm = Category_goodsVm(
            input:(
                refreshTriger:  rx.sentMessage(#selector(Category_Vc_goods.headerRefresh)).map { _ in () },
                loadMoreTriger: rx.sentMessage(#selector(Category_Vc_goods.footerRefresh)).map { _ in () }
            )
        )
        
        self.CategoryGoodListVm?
            .backDate
            .asObservable()
            .do(onNext:{[unowned self] _ in
                
                self.errorPageView.isHidden = true
                
            }).subscribe(onNext:{ data in
                
                self.showEmptyView = true
                self.goodsArr = data
                
            }).addDisposableTo(disposeBag)
        
        self.CategoryGoodListVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        //绑定错误
        self.CategoryGoodListVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.CategoryGoodListVm?.refresherror.asObserver().bindTo(self.rx_showerrorpage).addDisposableTo(disposeBag)
        self.errorPageView.reloadSubject.bindTo(self.CategoryGoodListVm!.reloadTrigger).addDisposableTo(disposeBag)
        
        self.errorPageView.reloadSubject.subscribe(onNext:{ _ in
            if self.isreloadType == false{
                self.CategoryGoodListVm?.ppturlStatus.value = self.pptid ?? ""
            }
        }).addDisposableTo(disposeBag)
        
        //判断是否还有数据如果有就继续加载,没有则提示已经展示全部
        self.CategoryGoodListVm?.hasNextPage.asDriver().asObservable().subscribe(onNext:{ hasNextPage in
            if !hasNextPage{
                self.footer.endRefreshingWithNoMoreData()
            }else{
                self.footer.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        
        
        self.GetSku = GetSkuVm()
        
        self.GetSku?.backSkuDate.skip(1).asObservable().subscribe(onNext:{ result in
            
            self.addCar(vc: self, model: result,footerButonType:"jrphd"){ product , param,_ in
                self.GetSku?.addcartsSubject.onNext(param["osCarts"] as! String as NSString)
            }
            
        }).addDisposableTo(disposeBag)
        
        self.GetSku?.addcartsSuccess.subscribe(onNext:{ data in
            
            _ = "orderformbadge".openURL()
            self.view.toastErrorCode(100041002)
            
            
            
        }).addDisposableTo(disposeBag)
        
        self.GetSku?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
}
extension Category_Vc_goods:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if goodsArr?.count != 0{
            return 1
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let modelArr = goodsArr{
            return modelArr.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Category_Goods_TableViewCell
        
        cell.add_PHD_Button.tag = indexPath.row
        cell.add_PHD_Button.addTarget(self, action: #selector(Category_Vc.add_JHD(_:)), for: .touchUpInside)
        
        if let modelArr = goodsArr{
            cell.item = modelArr[indexPath.row]
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 93
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let modelArr = self.goodsArr{
            _ = "productdetail".openURL(["pdid":"\(modelArr[indexPath.row].pdid)"])
        }
    }
}
extension Category_Vc_goods:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("该分类，暂无商品！\n换个分类试试吧～")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "brandproduct-empty", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}
